package com.qf.votesystem.interceptor;
import cn.hutool.jwt.JWT;
import com.qf.votesystem.Contants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
@Slf4j
public class Myinterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取手机号
        String phoneNum = request.getParameter("phoneNum");

        String headeToken = request.getHeader("voteToken"+phoneNum);

        if( headeToken==null || "".equals(headeToken)){

            String token = getToken();

            response.setHeader("voteToken"+phoneNum,token);

        }else {

            JWT jwt = JWT.of(headeToken);

            String stringTime = jwt.getPayload("time").toString();

            Long aLong = Long.valueOf(stringTime);

            //2.获取当前系统时间挫
            long currentTime = new Date().getTime();

            if((currentTime - aLong) > 60000){

                //3.生成token
                String token = getToken();
                response.setHeader("voteToken"+phoneNum,token);
        }
        }
        return true;
    }

    /**
     * 获取token 根据 JWT
     * @return
     */
    private String getToken() {

        String sign = JWT.create().setPayload("time", new Date().getTime())
                .setIssuer("vote2203")
                .setKey(Constants.SALT.getBytes(StandardCharsets.UTF_8))
                .sign();
        return sign;
    }
}
